from flask import Blueprint, request
from models import Member, UserLevel, Profession
from flask_jwt_extended import create_refresh_token, jwt_required, get_jwt_identity
from ext import db

_user = Blueprint('user', __name__)


@_user.route('/api/login', methods=['POST'])
def login():
    name = request.form['name']
    pwd = request.form['pwd']

    if name.isdigit():
        user = Member.query.filter(Member.id == name).first()
    elif '@' in name:
        user = Member.query.filter(Member.email == name).first()
    else:
        user = Member.query.filter(Member.name == name).first()

    if user is None:
        return "用户不存在", 400

    if user.checkPassword(pwd):
        refresh_token = create_refresh_token(identity={
            'id': user.id,
            'name': user.name,
            'type': user.Type,
            'phone': user.phone,
        })
        return {
            'refresh_token': refresh_token,
            'name': user.name,
            'id': user.id,
            'type': user.Type,
            'phone': user.phone,
        }
    else:
        return "用户名密码不匹配", 400


@_user.route('/api/changePwd', methods=['POST'])
@jwt_required(refresh=True)
def changePwd():
    pwd = request.form['pwd']

    cur = get_jwt_identity()
    stuID = cur['id']
    user = Member.query.filter(Member.id == stuID).first()
    user.setPassword(pwd)
    return "修改成功"


@_user.route('/api/getUser', methods=['GET'])
@jwt_required(refresh=True)
def get_User():
    cur = get_jwt_identity()
    return cur


@_user.route('/api/getAllUser', methods=['GET'])
@jwt_required(refresh=True)
def getALLUser():
    cur = get_jwt_identity()
    if '管理员' not in cur['type']:
        return "Permission Denied", 403
    usersR = Member.query.all()
    users = {}
    for i in usersR:
        users[i.id] = {
            'name': i.name,
            'grade': i.grade,
            'profession': i.profession,
            'birthday': i.birthday.strftime('%Y-%m-%d'),
            'phone': i.phone,
            'email': i.email,
            'type': i.Type,
        }
    return users


@_user.route('/api/changeUser', methods=['POST'])
@jwt_required(refresh=True)
def changeUser():
    cur = get_jwt_identity()
    if '管理员' not in cur['type']:
        return "Permission Denied", 403
    user = request.json
    temp = Member.query.filter(Member.id == user['id']).first()
    newUser = False
    if temp is None:
        temp = Member()
        temp.id = user['id']
        temp.Type = '成员'
        newUser = True
    temp.name = user['name']
    temp.phone = user['phone']
    temp.birthday = user['birthday']
    temp.profession = user['profession']
    temp.grade = user['grade']
    temp.email = user['email']
    if cur['type'] == '超级管理员':
        temp.Type = user['type']
    if newUser:
        temp.setPassword()
        db.session.add(temp)
    return '修改成功'


@_user.route('/api/deleteUser', methods=['POST'])
@jwt_required(refresh=True)
def deleteUser():
    cur = get_jwt_identity()
    if '管理员' not in cur['type']:
        return "Permission Denied", 403
    user = request.json['ids']
    users = Member.query.filter(Member.id.in_(user)).all()
    for i in users:
        if cur['type'] == '超级管理员' or (i.Type == '成员' and '管理员' in cur['type']):
            db.session.delete(i)
    return '删除成功'


@_user.route('/api/resetPwd', methods=['POST'])
@jwt_required(refresh=True)
def resetPwd():
    cur = get_jwt_identity()
    if '管理员' not in cur['type']:
        return "Permission Denied", 403
    users = request.json['ids']
    userRecords = Member.query.filter(Member.id.in_(users)).all()
    names = []
    for i in userRecords:
        if cur['type'] == '超级管理员' or (i.Type == '成员' and '管理员' in cur['type']):
            i.setPassword()
            names.append(i.name)
    return ','.join(names) + '的密码已被重置，请尽快修改密码'


@_user.route('/api/addUser', methods=['POST'])
@jwt_required(refresh=True)
def addUser():
    cur = get_jwt_identity()
    if '管理员' not in cur['type']:
        return "Permission Denied", 403
    new_users = request.json
    for i in new_users:
        new_one = Member()
        new_one.id = i['id']
        new_one.name = i['name']
        new_one.level = 1
        new_one.email = i['email']
        new_one.birthday = i['birthday']
        new_one.grade = i['grade']
        new_one.phone = i['phone']
        new_one.profession = i['profession']
        new_one.setPassword('emovieECNU@' + i['id'])
        db.session.add(new_one)
    return "添加成功！"


@_user.route('/api/userType', methods=['GET'])
def getUserType():
    userType = UserLevel.query.all()
    return {i.level: i.nickname for i in userType}


@_user.route('/api/userProfession', methods=['GET'])
def getUserProfession():
    userProfession = Profession.query.filter(Profession.available == 1).all()
    return {'profession': [i.profession for i in userProfession]}

